import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:ecy_app_flutter/ecycommon/EcyAPI.dart';
import 'package:ecy_app_flutter/routes/blind_box/exchange_market/models/blind_box_page.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import '../../../ecycommon/EcyRequestBaseManager.dart';
import '../../../ecycommon/utils/EcyLogger.dart';
import '../../../model/EcyApiCommonPage.dart';
import '../../../model/EcyApiCommonResponse.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../goods/model/CommodityTop.dart';

class BlindBoxMorePage extends StatefulWidget {
  const BlindBoxMorePage({required super.key, required this.ipCode, required this.ipName});
  
  final String ipCode;
  final String ipName;
  @override
  State<BlindBoxMorePage> createState() => _BlindBoxMorePageState();
}

class _BlindBoxMorePageState extends State<BlindBoxMorePage> {
  _BlindBoxMorePageState();

  final RefreshController _refreshControllerFirst = RefreshController(initialRefresh: false);
  final RefreshController _refreshControllerSec = RefreshController(initialRefresh: false);

  int _currentPage = 1;
  bool _hasMore = false;

  final List<int> indexList = List.filled(19, 0);
  final List<BlindBoxPageMore> _commodityMoreList = [];

  @override
  void initState() {
    super.initState();
    _refreshData("");
  }

  //无数据时下拉刷新
  Future<void> _onRefresh1() async {
    _currentPage = 1;
    await _refreshData("");
    // 重置上拉加载状态
    _refreshControllerFirst.refreshCompleted();
  }

  //下拉刷新
  Future<void> _onRefresh2() async {
    _currentPage = 1;
    await _refreshData("");
    _refreshControllerSec.refreshCompleted();
    // 重置上拉加载状态
    if (_hasMore) {
      _refreshControllerSec.loadComplete();
    } else {
      _refreshControllerSec.loadNoData();
    }
  }

  //上拉加载更多
  Future<void> _onLoading2() async {
    if (_hasMore) {
      _currentPage++;
      await _refreshData("");
      _refreshControllerSec.loadComplete();
    } else {
      _refreshControllerSec.loadNoData();
    }
  }

  Future<void> _refreshData(String search) async {
    try {
      Map<String, dynamic> body = {
        "current": _currentPage,
        "size": 10,
        "ipCode": widget.ipCode,
        "ipName": widget.ipName,
      };
      var response = await EcyRequestbasemanager().post(EcyAPI.blindBoxList.url, body);
      if (response != null) {
        var commonResponse = EcyApiCommonResponse.fromJson(response, (response) => json);
        if (commonResponse.code == 0 || commonResponse.code == 200) {
          EcyApiCommonPage<BlindBoxPageMore> commonPage =
              EcyApiCommonPage.fromJson(response["data"], (json) => BlindBoxPageMore.fromJson(json));
          _hasMore = (commonPage.pages ?? 0) > _currentPage;
          _currentPage = commonPage.current ?? 0;
          var commodityMoreList = commonPage.records ?? [];
          if (_currentPage == 1) {
            _commodityMoreList.clear();
          }
          setState(() {
            _commodityMoreList.addAll(commodityMoreList);
          });
        }
      }
    } catch (e) {
      EcyLogger.log("获取盲抽失败$e");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: const Color(0xFFFFF0F8),
        appBar: AppBar(
          title: Text(widget.ipName,
              style: TextStyle(
                  fontFamily: "PingFang SC",
                  fontWeight: FontWeight.w700,
                  fontSize: 16.sp,
                  color: const Color(0xFF262626))),
          centerTitle: true,
          backgroundColor: const Color(0xFFFFF0F8),
          leadingWidth: 50.w,
          scrolledUnderElevation: 0,
          leading: GestureDetector(
            behavior: HitTestBehavior.translucent,
            onTap: () {
              EcyRouter.pop(context, "");
            },
            child: Align(
              alignment: Alignment.centerRight,
              child: Image.asset(
                "assets/images/ic_back.png",
                width: 30.w,
              ),
            ),
          ),
        ),
        body: Flexible(
            child: Container(
                decoration: BoxDecoration(
                  color: const Color(0xFFFFFFFF), // 背景颜色
                  borderRadius:
                      BorderRadius.only(topLeft: Radius.circular(20.r), topRight: Radius.circular(20.r)), // 圆角边框
                ),
                padding: EdgeInsets.only(left: 16.w, top: 24.h, right: 16.w),
                child: SmartRefresher(
                  enablePullDown: true,
                  enablePullUp: true,
                  physics: const AlwaysScrollableScrollPhysics(),
                  header: const ClassicHeader(
                    refreshStyle: RefreshStyle.Follow,
                    idleText: '下拉刷新',
                    refreshingText: '加载中...',
                    completeText: '刷新完成',
                    failedText: '刷新失败',
                    textStyle: TextStyle(color: Color(0xFF8C8C8C), fontSize: 14),
                    releaseText: '松开刷新',
                    iconPos: IconPosition.top,
                    spacing: 8,
                  ),
                  footer: CustomFooter(
                    builder: (BuildContext context, LoadStatus? mode) {
                      Widget body;
                      if (mode == LoadStatus.idle) {
                        body = const Text("上拉加载更多", style: TextStyle(color: Color(0xFF8C8C8C)));
                      } else if (mode == LoadStatus.loading) {
                        body = const Text("加载中...", style: TextStyle(color: Color(0xFF8C8C8C)));
                      } else if (mode == LoadStatus.failed) {
                        body = const Text("加载失败，点击重试", style: TextStyle(color: Color(0xFF8C8C8C)));
                      } else if (mode == LoadStatus.canLoading) {
                        body = const Text("松手加载更多", style: TextStyle(color: Color(0xFF8C8C8C)));
                      } else {
                        body = const Text("没有更多上新了", style: TextStyle(color: Color(0xFF8C8C8C)));
                      }
                      return SizedBox(
                        height: 35.w,
                        child: Center(child: body),
                      );
                    },
                  ),
                  onRefresh: () => _onRefresh2(),
                  onLoading: () => _onLoading2(),
                  controller: _refreshControllerSec,
                  child: ListView.builder(
                    shrinkWrap: true,
                    physics: const ClampingScrollPhysics(),
                    itemCount: _commodityMoreList.length,
                    itemBuilder: (BuildContext context, int index) {
                      return GestureDetector(
                          child: Padding(
                            padding: EdgeInsets.only(bottom: 24.h),
                            child: _buildSizedBox(_commodityMoreList[index]),
                          ),
                          onTap: () {
                            EcyRouter.push(context, EcyRouter.blindBoxEnter, {
                              "commodityName": _commodityMoreList[index].commodityName, 
                              "ipCode": widget.ipCode,
                              "initialCommodityId": _commodityMoreList[index].commodityId,
                              "ipName": widget.ipName,
                            });
                          });
                    },
                  ),
                ))));
  }

  Widget avatar = Image.asset('assets/images/login_app_icon.png', width: 80.w, height: 80.h, fit: BoxFit.contain);

  SizedBox _buildSizedBox(BlindBoxPageMore? commodityMore) {
    return SizedBox(
      height: 110.h,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 109.w,
            height: 109.h,
            child: DecoratedBox(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(4.r), //3像素圆角
                border: Border.all(
                  color: const Color(0x10EA4B9B),
                  width: 2,
                ),
              ),
              child: Padding(
                padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 8.h),
                child: CachedNetworkImage(
                  width: 80.w,
                  height: 80.h,
                  imageUrl: commodityMore?.mainImageUrl ?? "",
                  imageBuilder: (context, imageProvider) => Container(
                    decoration: BoxDecoration(
                        borderRadius: BorderRadius.all(Radius.circular(8.r)),
                        image: DecorationImage(image: imageProvider, fit: BoxFit.cover)),
                  ),
                  placeholder: (context, url) => avatar,
                  errorWidget: (context, url, error) => avatar,
                ),
              ),
            ),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text(
                  commodityMore?.commodityName ?? "",
                  style: TextStyle(
                    fontFamily: "PingFang SC",
                    fontWeight: FontWeight.w700,
                    fontSize: 16.sp,
                    color: const Color(0xFF262626),
                  ),
                  maxLines: 2,
                  overflow: TextOverflow.ellipsis,
                ),
                Padding(
                  padding: EdgeInsets.only(bottom: 5.h),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      RichText(
                          textDirection: TextDirection.ltr,
                          textAlign: TextAlign.end,
                          text: TextSpan(children: [
                            WidgetSpan(
                              child: Padding(
                                padding: EdgeInsets.only(right: 9.w),
                                child: Text(
                                  commodityMore?.salePrice.toString() ?? "",
                                  style: TextStyle(
                                    fontFamily: "PingFang SC",
                                    fontSize: 14.sp,
                                    fontWeight: FontWeight.w700,
                                    color: const Color(0xFFF55F4E),
                                  ),
                                ),
                              ),
                            ),
                            WidgetSpan(
                                child: Text(
                              "￥${commodityMore?.originalPrice.toString() ?? ""}",
                              style: TextStyle(
                                fontFamily: "PingFang SC",
                                fontSize: 14.sp,
                                fontWeight: FontWeight.w500,
                                color: const Color(0xFF8C8C8C),
                              ),
                            )),
                          ])),
                      SizedBox(
                        width: 70.w, // 设置宽度
                        height: 28.h, // 设置高度
                        child: TextButton(
                          onPressed: () {
                            EcyRouter.push(context, EcyRouter.blindBoxEnter, {
                              "commodityName": commodityMore?.commodityName, 
                              "ipCode": widget.ipCode,
                              "initialCommodityId": commodityMore?.commodityId,
                              "ipName": widget.ipName,
                            });
                          },
                          style:
                              TextButton.styleFrom(backgroundColor: const Color(0xFFEA4B9B), padding: EdgeInsets.zero),
                          child: Text(
                            "立即抽",
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 14.sp,
                              fontFamily: "PingFang SC",
                              fontWeight: FontWeight.w700,
                            ),
                          ),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _refreshControllerFirst.dispose();
    _refreshControllerSec.dispose();
    super.dispose();
  }
}
